//
//  AETabbarView.m
//  Pods
//
//  Created by 徐 洋 on 14/11/27.
//
//

#import <PixateFreeStyle.h>

#import "AETabbarView.h"

static const CGFloat TabbarButtonHeight = 90.0f;
static const CGFloat TabbarButtonWidth = 108.0f;//125.0f;//150.0f
static const CGFloat TabbarButtonMargin = 15.0f;//0.0f;

@interface AETabbarButton : UIButton

@property (nonatomic, strong) NSString * redirectURL;

@end

@implementation AETabbarButton

@end

@interface AETabbarView()

@property (nonatomic, strong) NSDictionary * config;

@end

@implementation AETabbarView

- (id)initWithConfig:(NSDictionary *)config
{
    self = [super init];
    if (self) {
        // Initialization code
        self.styleClass = @"tabbar";
        [self buildButtonsWithConfiguration:config];
    }
    return self;
}

- (void)buildButtonsWithConfiguration:(NSDictionary *)config
{
    BOOL hidden = config[kTabbarHidden]?([config[kTabbarHidden] boolValue]):YES;
    
    if (hidden) {
        return;
    }
    
    NSArray * buttonSpecs = config[kTabbarItems];
    
    NSMutableArray * buttons = [NSMutableArray arrayWithCapacity:[buttonSpecs count]];
    
    __block UIView * lastItem = nil;
    
    [buttonSpecs enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        NSDictionary * spec = obj;
        
        AETabbarButton * tabbarBtn = [AETabbarButton buttonWithType:UIButtonTypeCustom];
        tabbarBtn.styleClass = NSLocalizedString([spec objectForKey:kTabbarIcon],nil);
        
        if (spec[kTabbarTitle]) {
            [tabbarBtn setTitle:spec[kTabbarTitle] forState:UIControlStateNormal];
            [tabbarBtn setTitleColor:[UIColor clearColor] forState:UIControlStateNormal];
        }
        
        
        if ([spec[kTabbarType] isEqualToString:kTabbarTypeRedirect]) {
            tabbarBtn.redirectURL = spec[kTabbarURL];
            [tabbarBtn addTarget:self action:@selector(redirect:) forControlEvents:UIControlEventTouchUpInside];
        }
        else {
            tabbarBtn.tag = [spec[kTabbarVCIndex] integerValue];
            [tabbarBtn addTarget:self action:@selector(buttonTapped:) forControlEvents:UIControlEventTouchUpInside];
        }
        
        [tabbarBtn setBackgroundColor:[UIColor blueColor]];
        
        [self addSubview:tabbarBtn];
        [buttons addObject:tabbarBtn];
        
        // Using auto layout constraits
        
        [tabbarBtn setTranslatesAutoresizingMaskIntoConstraints:NO];
        
        if (lastItem == nil) {
            lastItem = tabbarBtn;
            CGFloat totalWidth = (TabbarButtonWidth + TabbarButtonMargin) * [buttonSpecs count] - TabbarButtonMargin;
            
            [self addConstraint:[NSLayoutConstraint constraintWithItem:tabbarBtn attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterY multiplier:1.0f constant:1.0f]];
            [self addConstraint:[NSLayoutConstraint constraintWithItem:tabbarBtn attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeRight multiplier:0.5f constant:-0.5 * totalWidth]];
            [self addConstraint:[NSLayoutConstraint constraintWithItem:tabbarBtn attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0f constant:TabbarButtonWidth]];
            [self addConstraint:[NSLayoutConstraint constraintWithItem:tabbarBtn attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0f constant:TabbarButtonHeight]];
            
            return;
        }
        
        [self addConstraint:[NSLayoutConstraint constraintWithItem:tabbarBtn attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:lastItem attribute:NSLayoutAttributeCenterY multiplier:1.0f constant:0.0f]];
        [self addConstraint:[NSLayoutConstraint constraintWithItem:tabbarBtn attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:lastItem attribute:NSLayoutAttributeTrailing multiplier:1.0f constant:TabbarButtonMargin]];
        [self addConstraint:[NSLayoutConstraint constraintWithItem:tabbarBtn attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:lastItem attribute:NSLayoutAttributeWidth multiplier:1.0f constant:0.0f]];
        [self addConstraint:[NSLayoutConstraint constraintWithItem:tabbarBtn attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:lastItem attribute:NSLayoutAttributeHeight multiplier:1.0f constant:0.0f]];
        
        lastItem = tabbarBtn;
    }];
}

- (void)buttonTapped:(id)object
{
    UIButton * button = object;
    
    NSInteger index = button.tag;

    if (self.delegate) {
        [self.delegate tabbar:self didSelectedAtIndex:index];
    }
}

- (void)redirect:(UIButton *)button
{
    NSURL * url = [NSURL URLWithString:((AETabbarButton *)button).redirectURL];
    
    if ([[UIApplication sharedApplication] canOpenURL:url]) {
        [[UIApplication sharedApplication] openURL:url];
    }
    else {
        UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"提示" message:[NSString stringWithFormat:@"\"%@\"软件未安装!",[button titleForState:UIControlStateNormal]] delegate:nil cancelButtonTitle:@"确认" otherButtonTitles:nil];
        
        [alert show];
        [NSTimer scheduledTimerWithTimeInterval:3.0f target:self selector:@selector(closeAlertView:) userInfo:@{@"alertView":alert} repeats:NO];
    }
}

- (void)closeAlertView:(NSTimer *)timer
{
    UIAlertView * alert = [timer.userInfo objectForKey:@"alertView"];
    [alert dismissWithClickedButtonIndex:0 animated:YES];
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

@end
